import matplotlib.pyplot as plt
import matplotlib.animation as animation
import subprocess
import argparse
import re
import os

# log_path = "./logfile.log"  # Replace with the actual log file path

# Setup global plot style
plt.rcParams.update({
	'font.family': 'sans-serif',
	'font.sans-serif': ['DejaVu Sans'],  # or another font listed as available
	'font.size': 12,
	'axes.titlesize': 14,
	'axes.titleweight': 'bold'
})

def get_packet_counts(log_path):
	try:
		# Check if the log file exists
		if not os.path.isfile(log_path):
			raise FileNotFoundError(f"Log file '{log_path}' not found.")

		output = subprocess.run(["tail", "-n", "6", log_path], capture_output=True, text=True, check=True)
	except FileNotFoundError as e:
		print(e)
		return [], []  # Return empty lists if the file is not found
	except subprocess.CalledProcessError as e:
		print(f"Failed to load the log file: {e}")
		return [], []  # Return empty lists if there's an issue running the subprocess

	lines = output.stdout.strip().split("\n")

	received_packets = []
	lost_packets = []
	for line in lines:
		recv_match = re.search(r"total_recv_packet:(\d+)", line)
		loss_match = re.search(r"total_loss_packet_count:(\d+)", line)
		if recv_match and loss_match:
			received_packets.append(int(recv_match.group(1)))
			lost_packets.append(int(loss_match.group(1)))

	return received_packets, lost_packets


def animate(i, log_path):
	received_packets, lost_packets = get_packet_counts(log_path)

	if received_packets and lost_packets:
		x_data.append(i)
		recv_data.append(received_packets[-1])
		loss_data.append(lost_packets[-1])

		ax.clear()

		ax.plot(x_data, recv_data, color='blue', linewidth=2, label='Received packet', zorder=3)
		ax.plot(x_data, loss_data, color='#d62728', linestyle='--', linewidth=2, label='Loss Packet', zorder=2)

		ax.set_title("VBSLite Received and Lost Packet Count Results (300Topics)", fontsize=14,  pad = 10, fontweight='bold')
		ax.set_ylabel("Packet Count")
		ax.set_xlabel("Time (seconds)")
		ax.set_xlim(0, i+10)
		ax.set_ylim(-i - 10, max(max(recv_data, default=0), max(loss_data, default=0)) + 100)

		ax.spines['top'].set_visible(False)
		ax.spines['right'].set_visible(False)

		ax.annotate('', xy=(1.01, 0), xycoords='axes fraction',
					xytext=(1.0, 0),
					arrowprops=dict(arrowstyle="->", color='black'))
		ax.annotate('', xy=(0, 1.01), xycoords='axes fraction',
					xytext=(0, 1.0),
					arrowprops=dict(arrowstyle="->", color='black'))

		ax.legend(loc='center', frameon=True, framealpha=0.95, edgecolor='#333333')

def main():
	global ax, x_data, recv_data, loss_data

	x_data, recv_data, loss_data = [], [], []
	parser = argparse.ArgumentParser(description='Process log file for RAM usage.')
	parser.add_argument('-f', '--file', required=True, help='Path to the log file')

	args = parser.parse_args()


	fig, ax = plt.subplots(figsize=(10, 6))

	plt.tight_layout()
	plt.subplots_adjust(left=0.1, right=0.9, bottom=0.1, top=0.9)

	# Disable frame caching
	ani = animation.FuncAnimation(fig, animate, fargs=(args.file,), interval=500, cache_frame_data=False)

	plt.show()

if __name__ == "__main__":
	main()